import {Component, ElementRef, EventEmitter, Input, OnInit, Output, Renderer, ViewChild} from '@angular/core';
import {environment} from '../../../environments/environment';
import {StorageService} from '../../services/storage.service';
// import * as wangEditor from 'wangeditor/release/wangEditor.js';
declare var E: any;
@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})
export class EditorComponent implements OnInit {


    private editor: any;
    @ViewChild('editorElem') editorElem: ElementRef;
    @Output() onPostData = new EventEmitter();
    @Input() uploadImageUrl: string;
    @Input() content: string;
    ip: string;

    constructor(private el: ElementRef,
                private storageService: StorageService) { }
    ngOnInit(): void {
        this.ip = environment.url.management;
    }
    ngAfterViewInit() {
         let E = window['wangEditor'];
        // let editordom = this.el.nativeElement.querySelector('#editorElem');
        this.editor = new E(this.editorElem.nativeElement);
        this.editor.customConfig.uploadImgServer  = this.uploadImageUrl;
        this.editor.customConfig.pasteIgnoreImg = true; // 倒链过滤
        this.editor.customConfig.uploadImgParams = {
            access_token: this.storageService.getToken('token')
        };
        this.editor.customConfig.uploadFileName = 'file';
        this.editor['customConfig'].customAlert = function (info) {
            // info 是需要提示的内容
            // alert('自定义提示：' + info)
        };
        this.editor.customConfig.uploadImgHooks = {
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
            customInsert: function (insertImg, result, editor) {
                // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
                // console.log(result);
                if (result['errcode'] === '00000'){
                    // console.log(result['datas'][0]['path']);
                    insertImg(`${environment.url.management}/${result['datas'][0]['path']}`);
                }
                // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                // let url = result.url;
                // insertImg(url);

                // result 必须是一个 JSON 格式字符串！！！否则报错
            }
        };
        this.editor.create();
    }

    clickHandle(): any {
        let data = this.editor.txt.html();
        return data;
    }
    setContent = (content) => {
        // console.log(content, content);
        this.editor.txt.html(content);
    }

}
